package com.buildings.activity;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.buildings.R;
import com.buildings.api.Api;
import com.buildings.api.Constant;
import com.buildings.base.BaseActivity;
import com.buildings.bean.AppUpdateResultBean;
import com.buildings.bean.LoginBean;
import com.buildings.bean.UserInfoBean;
import com.buildings.dialog.UpdateAppDialog;
import com.buildings.http.BaseCallBack;
import com.buildings.http.JsonBuilder;
import com.buildings.http.MyHttpClient;
import com.buildings.permissions.Acp;
import com.buildings.permissions.AcpListener;
import com.buildings.permissions.AcpOptions;
import com.buildings.util.CustomToast;
import com.buildings.util.DialogUtils;
import com.buildings.util.SPUtil;
import com.buildings.util.UpdateManager;
import com.buildings.util.Utils;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;

import org.json.JSONException;

import java.io.IOException;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;


public class MainTabActivity extends BaseActivity implements View.OnClickListener {

    @BindView(R.id.btn_task_list)
    Button btnTask;
    @BindView(R.id.btn_user)
    Button btnUser;
    @BindView(R.id.iv_head)
    ImageView ivHead;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_name_top)
    TextView tvNameTop;

    private Dialog myDialog;

    private LogoutReceiver logoutReceiver;

    private UpdateManager mUpdateManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maintab);
        ButterKnife.bind(this);
        myDialog = DialogUtils.showRefreshDialog(activity);
        String userId = (String) SPUtil.get("userId","");
        getUserInfo(userId);
        logoutReceiver = new LogoutReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("action.logout");
        registerReceiver(logoutReceiver,intentFilter);
        mUpdateManager = new UpdateManager(this);
    }



    @OnClick({R.id.btn_user,R.id.btn_task_list,R.id.iv_head})
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_user:
                startActivity(new Intent(activity,UserActivity.class));
                break;
            case R.id.btn_task_list:
                startActivity(new Intent(activity,TaskListActivity.class));
                break;
            case R.id.iv_head:

                break;
        }
    }

    private void getUserInfo(String userId) {


        MyHttpClient
                .newBuilder()
                .get()
                .url(Api.USER_INFO+"?userId="+userId)
//                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<UserInfoBean>() {
                    @Override
                    public void onSuccess(UserInfoBean bean) {
                        super.onSuccess(bean);
                        //{"code":200,"data":{"userId":"ca3ca0d0d557424d94ec8009b6ca6d08","userCode":"18434163012","userName":"sjadmin","sex":"1","sort":null,"birthday":"","officePhone":"","mobilePhone":"18434163012","fax":"","email":"","zwId":"","directLeader":"","extend1":"","extend2":"","extend3":"","extend4":"","extend5":"","extend6":"","extend7":"","extend8":"","extend9":"","extend10":"","isValid":"1","createUser":"c8f1ba6c7cf842409aba43206e9f7442","createTime":"2020-05-09T07:16:01.000+0000","updateUser":"c8f1ba6c7cf842409aba43206e9f7442","updateTime":"2020-05-15T07:06:47.000+0000","idCard":null,"theme":null},"message":null}
                        if(bean != null && bean.getCode() == 200){
                            if(bean.getData()!= null){
                                if(!TextUtils.isEmpty(bean.getData().getUserName())){
                                    SPUtil.save("userName",bean.getData().getUserName());
                                    tvName.setText(bean.getData().getUserName());
                                    String name = bean.getData().getUserName();
                                    char first = name.charAt(0);
                                    tvNameTop.setText(first+"");
//                                    tvNameTop.setText("热");
                                }
                            }

                        }
                        if (myDialog != null)
                            myDialog.dismiss();
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(activity, "网络异常");
                    }

                    @Override
                    public void onError(int code) {
                        super.onError(code);
                        if (myDialog != null)
                            myDialog.dismiss();
                        CustomToast.showToast(activity, "网络异常");
                    }
                });

    }


    class LogoutReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Utils.logout(activity);
            finish();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(logoutReceiver != null){
            unregisterReceiver(logoutReceiver);
        }
    }

    /*
   版本更新检查
    */
    private void updateHttp() {
//        String json = "{\"code\":200,\"data\":{\"appId\":\"4a9501b6067640e3ae42bbd194f42784\",\"appUrl\":\"https://www.datacollection.cn/BuildingCollectSystem/fwsjcj.apk\",\"appUpdateContent\":\"313\",\"appVersion\":\"V2.1\",\"createTime\":\"2020-07-30T01:57:53.000+0000\",\"delFlag\":\"0\",\"appType\":\"Android\"},\"message\":null}";
//        Gson gson = new Gson();
//        AppUpdateResultBean bean = gson.fromJson(json,AppUpdateResultBean.class);
//        if(bean != null && bean.getCode() == 200 && bean.getData() != null){
//            String versionName = bean.getData().getAppVersion();
//            String versionUpdateInfo = bean.getData().getAppUpdateContent();
//            String downloadUrl = bean.getData().getAppUrl();
//            boolean isForce = false;
//            if (!TextUtils.equals(Utils.getVersion(activity),versionName)) {
//                askMultiPermission(versionName,versionUpdateInfo,isForce,downloadUrl);
//            }
//        }

        JsonBuilder jsonBuilder = new JsonBuilder(this);
        jsonBuilder.put("type", Constant.APP_SOURCE);
        MyHttpClient
                .newBuilder()
                .post()
                .url(Api.APP_UPDATE)
                .addParam(jsonBuilder.toJsonString())
                .build()
                .enqueue(new BaseCallBack<AppUpdateResultBean>() {
                    @Override
                    public void onSuccess(AppUpdateResultBean bean) {
                        super.onSuccess(bean);
                        if(bean != null && bean.getCode() == 200 && bean.getData() != null){
                            String versionName = bean.getData().getAppVersion();
                            String versionUpdateInfo = bean.getData().getAppUpdateContent();
                            String downloadUrl = bean.getData().getAppUrl();
                            boolean isForce = false;
//                            if(jsonObject.has("flag")){
//                                isForce = jsonObject.getBoolean("flag");
//                            }
                            if (!TextUtils.equals(Utils.getVersion(activity),versionName)) {
                                askMultiPermission(versionName,versionUpdateInfo,isForce,downloadUrl);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call call, IOException e) {
                        super.onFailure(call, e);

                    }
                });

    }

    private void askMultiPermission(final String versionName, final String versionUpdateInfo, final boolean isForce, final String downloadUrl) {
        Acp.getInstance(this).
                request(new AcpOptions.Builder()
                                .setPermissions( Manifest.permission.READ_EXTERNAL_STORAGE,
                                        Manifest.permission.WRITE_EXTERNAL_STORAGE)

                                /*以下为自定义提示语、按钮文字
                                .setDeniedMessage()
                                .setDeniedCloseBtn()
                                .setDeniedSettingBtn()
                                .setRationalMessage()
                                .setRationalBtn()*/

                                .build(),
                        new AcpListener() {
                            @Override
                            public void onGranted() {
                                //getIMEI();
                                mUpdateManager.setUpdateParms(downloadUrl, versionName, versionUpdateInfo, isForce);
                                Intent intent = new Intent(activity, UpdateAppDialog.class);
                                intent.putExtra("path",downloadUrl);
                                intent.putExtra("version",versionName);
                                intent.putExtra("content",versionUpdateInfo);
                                intent.putExtra("force",isForce);
                                startActivityForResult(intent,2000);
                            }

                            @Override
                            public void onDenied(List<String> permissions) {
                                CustomToast.showToast(activity,"更新应用需要存储权限，请去管理界面授权");
                            }
                        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == 2000 && resultCode == RESULT_OK){
            mUpdateManager.showDownloadDialog();
        }
    }

}
